package com.cyam.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
/**
 * 
 * @author CourageAQ
 * 使用MultipartFile上传文件类
 */
public abstract class UploadUtil {
	

	/**上传文件*/
	public static String uploadFile(MultipartFile file,HttpServletRequest request,String filiUrl) {
		//定义返回结果，包含返回码和名称
		String resultJson = "{'code': 0,'msg': '' ,'fileName':'','uploadUrl':'' } ";
		String msg = ""; String code = "";
		String uploadUrl = "";
		if (StringUtils.isBlank(filiUrl)) {
			uploadUrl = Constants.DEFAULT_UPLOAD_URL;
		}else{
			uploadUrl = Constants.DEFAULT_UPLOAD_URL+filiUrl;
		}
		//定义上传路径
		String path = request.getSession().getServletContext().getRealPath(uploadUrl);
		
		try {
			//获取文件名
			String filename = file.getOriginalFilename();
			//重命名文件名，并将文件格式全部小写
			/*filename = Long.toString(new Date().getTime()) 
					+ filename.substring(filename.lastIndexOf(".")).toLowerCase();*/
			filename = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) 
					+ filename.substring(filename.lastIndexOf(".")).toLowerCase();
			File fileTarget = new File(path, filename);
			if (!fileTarget.exists()) {
				fileTarget.mkdirs();
			}
			//写入磁盘
			file.transferTo(fileTarget);
			//返回结果
			code= "200";
			msg = file.getOriginalFilename();
			resultJson = "{\"code\": \""+code+ "\",\"msg\": \"" +msg+"\",\"fileName\": \""+filename+"\",\"uploadUrl\":\"" + uploadUrl+"\"}";
			return resultJson;
		} catch (Exception e) {
			e.printStackTrace();
			code = "500";
			resultJson = "{\"code\": \""+code+"\",\"msg\": \"上传失败\",\"fileName\": \"上传失败\"}";
			return resultJson;
		}
	}
	/**
	 * 删除文件
	 * @param request
	 * @return 状态码
	 */
	public int deleteFile(HttpServletRequest request,String filename){
		String path = request.getSession().getServletContext().getRealPath("/upload/" + filename);
		File file = new File(path);
		try {
			if (file.exists()) {
				file.delete();
			}
			return 200;
		} catch (Exception e) {
			e.printStackTrace();
			return 500;
		}
	}
}
